package com.aij.starter.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

import com.alibaba.fastjson.JSON;

public class StreamClient {
	
    public interface StreamCallback {
        void callback(String txt);
    }
    
	/**
	 * POST(对象参数)
	 * @param url
	 * @param param
	 */
	public void postEventStream(String url, Object req, StreamCallback cb) {
        InputStream is = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Accept", "text/event-stream");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream os = conn.getOutputStream();
            String json = JSON.toJSONString(req);
            os.write(json.getBytes("utf-8"));
            os.flush();
            os.close();
            is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while ((line = reader.readLine()) != null) {
                if (line.length() > 0) {
                	line = line.replaceFirst("data: ", "");
                    //System.out.println(line);
                    if (cb != null) {
                    	cb.callback(line);
                    }
                }
	        }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (!Objects.isNull(is)) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
